package com.ruoyi.websocket;

import com.ruoyi.websocket.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/listen/order/{carCode}")
public class OrderChanel {

    private static Map<String,Session> drivers = new ConcurrentHashMap();

    @OnOpen
    public void onOpen(Session session, @PathParam("carCode") String carCode){
        System.out.println("open...."+carCode);
        //保存司机信息，方便推单时根据carCode找到司机的长连接
        drivers.put(carCode,session);
        //将用户的身份信息装入session，方便在onClose、onMessage、onError的时候取到用户信息
        session.getUserProperties().put("carCode",carCode);
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("close....");
        //获取是谁断开了连接
        String carCode = (String) session.getUserProperties().get("carCode");
        //根据车牌号删除redis中的车辆位置数据
        StringRedisTemplate stringRedisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
        stringRedisTemplate.opsForGeo().remove("beijing-driver-geo",carCode);
    }

    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println(message);
        String[] location = message.split(",");
        String carCode = (String) session.getUserProperties().get("carCode");
        //存储司机最新的位置信息到redis-geo
        Point point = new Point(Double.parseDouble(location[0]), Double.parseDouble(location[1]));

        StringRedisTemplate stringRedisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
        try {
            stringRedisTemplate.opsForGeo().add("beijing-driver-geo", point, carCode);
        }catch (Exception e){
            e.printStackTrace();
        }


        //将司机每一个上报的坐标数据存入HBase

    }

    @OnError
    public void onError(Session session, Throwable throwable){

    }

    public static boolean sendMessage(String carCode, String message) throws IOException {
        Session session = drivers.get(carCode);
        System.out.println(session);
        if(session == null){
            return false;
        }

        session.getBasicRemote().sendText(message);
        return true;
    }

}
